package com.zty.controller;

import com.zty.DTO.FileChunkDTO;
import com.zty.response.CommonResponse;
import com.zty.service.FileService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

/**
 * @Author ZTY
 * @Description 文件上传下载（读&写）接口
 * @Date 1:54 2023-12-25
 **/

@Validated
@RestController
@RequestMapping("/file")
public class FileController {

    private final FileService fileService;

    public FileController(FileService fileService) {
        this.fileService = fileService;
    }

    /**
     * 文件的某个分片上传
     * @Valid  是用于校验的注解，若某个字段没填会给出自定义的异常信息
     * @param fileChunkDTO  文件的某个分片
     * @return
     */
    @PostMapping("/write")
    public CommonResponse<String> write(@Valid @RequestBody FileChunkDTO fileChunkDTO){
        String fileMd5 = fileService.write(fileChunkDTO);
        return CommonResponse.success(fileMd5);
    }

    @GetMapping("/read")
    public CommonResponse<?> read(@RequestParam("filename") @NotBlank(message = "文件名不得为空") String filename,
                                  @RequestParam("extension") String extension,
                                  @RequestParam("chunkNo") @NotNull(message = "文件分片序号不得为空") Integer chunkNo,
                                  @RequestParam("bucketName") @NotBlank(message = "存储桶名不得为空") String bucketName){
        byte[] content = fileService.read(filename,extension,chunkNo,bucketName);

        //  返回字节流即可，因为后期要将所有的文件分片去做一个组装
        return CommonResponse.success(content);
    }
}
